//
//  UserAccount.swift
//  JJWeibo
//
//  Created by JJ on 15/9/4.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding{
    
    var access_token:String?
    var expires_in:NSTimeInterval=0{
        didSet{
            expiresDate=NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate:NSDate?
    var uid:String?
    var avatar_large:String?
    var name:String?
    
    init(dic:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    
    override var description:String{
        let keys=["access_token","expires_in","uid","expiresDate","avatar_large","name"]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    
   static let path=(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    func saveUserAcount(){
        NSKeyedArchiver.archiveRootObject(self, toFile:UserAccount.path)
    }
    
    class func loadUserAccount() -> UserAccount? {
        // 解档加载用户账户的时候，需要判断 token 的有效期
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount
        
        if let date = account?.expiresDate {
            // 比较日期 date > NSDate() 结果是降序
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        
        return nil
    }
       
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_hd")
        aCoder.encodeObject(name, forKey: "name")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token=aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate=aDecoder.decodeObjectForKey("expiresDate")as?NSDate
        uid=aDecoder.decodeObjectForKey("uid")as?String
        avatar_large=aDecoder.decodeObjectForKey("avatar_hd")as?String
        name=aDecoder.decodeObjectForKey("name")as?String
    }
    
}
